package com.example.cdpbookstore.web.filter;

import com.example.cdpbookstore.pojo.entity.Customer;
import com.example.cdpbookstore.service.CustomerService;
import com.example.cdpbookstore.service.impl.CustomerServiceImpl;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 每次请求自动更新 session 中 customer
 */
@WebFilter(filterName = "AutoUpdateFilter", urlPatterns = "/*")
public class AutoUpdateFilter implements Filter {
    private final CustomerService customerService = new CustomerServiceImpl();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        HttpSession session = req.getSession();
        Customer customer = (Customer) session.getAttribute("customer");

        if (customer != null) {
            Customer customerDb = customerService.getById(customer.getId());
            if (customerDb != null) {
                session.setAttribute("customer", customerDb);
            }
        }

        chain.doFilter(req, resp);
    }

    @Override
    public void destroy() {
    }
}
